/*
 * Copyright (c) 2013-2014, starteasy Inc. All Rights Reserved.
 * 
 * Project Name: sample
 * $Id:  2016-11-14 17:11:26 $ 
 */
package cn.starteasy.sample.web.controller.api;

import cn.starteasy.core.common.domain.persistent.SearchEnum;
import cn.starteasy.core.common.domain.persistent.utils.ConditionBuilder;
import cn.starteasy.core.common.domain.wrapper.BooleanWrapper;
import cn.starteasy.sample.service.ICityService;
import cn.starteasy.core.common.domain.view.admin.SearchField;
import cn.starteasy.core.common.domain.wrapper.StringWrapper;
import cn.starteasy.core.common.domain.view.BizData4Page;
import cn.starteasy.core.common.exception.BizException;
import cn.starteasy.core.common.protocol.utils.RtnCodeEnum;

import cn.starteasy.sample.domain.City;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/api")
public class ApiCityController{
    private static final Logger logger = LoggerFactory.getLogger(ApiCityController.class);

    @Autowired
    private ICityService cityService;

   /**
     * 新增 城市
     * @param city
     * @return  处理条数
     */
    @ResponseBody
    @RequestMapping(value = "/city", method = RequestMethod.POST)
    public Object addCity(@RequestBody City city) {
        try {
            String msg = "";

            if(city==null) {
                msg = "添加城市参数不正确";
            }else if(city.getStatus() != null){
                msg = "城市状态不能为空";
            }else if(city.getCreator() != null){
                msg = "城市创建人不能为空";
            }else if(city.getCreateDate() != null){
                msg = "城市创建时间不能为空";
            }else if(city.getLastModifier() != null){
                msg = "城市修改人不能为空";
            }else if(city.getLastModDate() != null){
                msg = "城市修改时间不能为空";
            }

            if(StringUtils.isNotBlank(msg)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), msg);
            }

            cityService.create(city);
            return new BooleanWrapper(true);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "新增城市异常");
        }
    }


    /**
     * 删除 城市
     *
     * @param {cityId} 城市ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/city/{cityId}" ,method = RequestMethod.DELETE)
    public Object delCity(@PathVariable String cityId) {
        try {
            if(StringUtils.isBlank(cityId)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "删除城市失败，参数不正确");
            }
            cityService.deleteByCondition(ConditionBuilder.condition("id", SearchEnum.eq, cityId));
            return new BooleanWrapper(true);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "删除城市异常");
        }
    }


    /**
     * 修改城市数据
     * @param city 提交上来的城市JSON数据
     * @param cityId  城市ID
     * @return  修改条数
     */
    @ResponseBody
    @RequestMapping(value = "/city/{cityId}", method = RequestMethod.PATCH)
    public StringWrapper editCity(@RequestBody City city, @PathVariable String cityId) {
        try {
            String msg = "";
            if(city==null) {
                msg = "添加城市参数不正确";
            }else if(city.getStatus() != null){
                msg = "城市状态不能为空";
            }else if(city.getCreator() != null){
                msg = "城市创建人不能为空";
            }else if(city.getCreateDate() != null){
                msg = "城市创建时间不能为空";
            }else if(city.getLastModifier() != null){
                msg = "城市修改人不能为空";
            }else if(city.getLastModDate() != null){
                msg = "城市修改时间不能为空";

            }

            if(StringUtils.isNotBlank(msg)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), msg);
            }

            City city_old = (City) cityService.view(city.getId());
            if(city==null) {
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改失败，系统未找到相关数据");
            }

            if(city.getId() != null){
                city_old.setId(city.getId());
            }
            if(!StringUtils.isBlank(city.getName())){
                city_old.setName(city.getName());
            }
            if(!StringUtils.isBlank(city.getNumber())){
                city_old.setNumber(city.getNumber());
            }
            if(!StringUtils.isBlank(city.getXpoint())){
                city_old.setXpoint(city.getXpoint());
            }
            if(!StringUtils.isBlank(city.getYpoint())){
                city_old.setYpoint(city.getYpoint());
            }
            if(!StringUtils.isBlank(city.getProvinceId())){
                city_old.setProvinceId(city.getProvinceId());
            }
            if(city.getStatus() != null){
                city_old.setStatus(city.getStatus());
            }
            if(city.getCreator() != null){
                city_old.setCreator(city.getCreator());
            }
            if(city.getCreateDate() != null){
                city_old.setCreateDate(city.getCreateDate());
            }
            if(city.getLastModifier() != null){
                city_old.setLastModifier(city.getLastModifier());
            }
            if(city.getLastModDate() != null){
                city_old.setLastModDate(city.getLastModDate());
            }


            int row=cityService.edit(city_old);
            if(row > 0) {
                return new StringWrapper("修改城市成功");
            }else{
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改城市失败");
            }
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改城市数据异常");
        }
    }


    /**
     * 获取单城市实体
     *
     * @param cityId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/city/{cityId}", method = RequestMethod.GET)
    public City getCity(@PathVariable String cityId) {
        try {
            if(StringUtils.isBlank(cityId)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "参数不正确！");
            }
            Map<String,Object> whereParams = new HashMap<String, Object>();
            whereParams.put("id", cityId);
            City city= (City) cityService.viewOne(null, whereParams, null);
            if(null == city){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "系统未找到城市相关数据！");
            }
            return city;
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "获取单城市实体异常");
        }
    }


    /**
     * 城市数据输出 带分页
     *
     * @param city 过滤条件
     * @param page      第几页
     * @return 业务数据列表实体，最终转换为json数据输出
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/citylist", method = RequestMethod.POST)
    public BizData4Page citylist(City city, Integer page) {
        try {
            Map<String, Object> whereParams = new HashMap<String, Object>();
            if(city.getId() != null){
                whereParams.put("id", new SearchField("id", "=", city.getId()));
            }
            if(!StringUtils.isBlank(city.getName())){
                whereParams.put("name", new SearchField("name", "like", "%" + city.getName() + "%"));
            }
            if(!StringUtils.isBlank(city.getNumber())){
                whereParams.put("number", new SearchField("number", "like", "%" + city.getNumber() + "%"));
            }
            if(!StringUtils.isBlank(city.getXpoint())){
                whereParams.put("xpoint", new SearchField("xpoint", "like", "%" + city.getXpoint() + "%"));
            }
            if(!StringUtils.isBlank(city.getYpoint())){
                whereParams.put("ypoint", new SearchField("ypoint", "like", "%" + city.getYpoint() + "%"));
            }
            if(!StringUtils.isBlank(city.getProvinceId())){
                whereParams.put("provinceId", new SearchField("provinceId", "like", "%" + city.getProvinceId() + "%"));
            }
            if(city.getStatus() != null){
                whereParams.put("status", new SearchField("status", "=", city.getStatus()));
            }
            if(city.getCreator() != null){
                whereParams.put("creator", new SearchField("creator", "=", city.getCreator()));
            }
            if(city.getCreateDate() != null){
                whereParams.put("createDate", new SearchField("createDate", "=", city.getCreateDate()));
            }
            if(city.getLastModifier() != null){
                whereParams.put("lastModifier", new SearchField("lastModifier", "=", city.getLastModifier()));
            }
            if(city.getLastModDate() != null){
                whereParams.put("lastModDate", new SearchField("lastModDate", "=", city.getLastModDate()));
            }


            //other props filter
            whereParams.put("groupOp", "and");

        return cityService.queryPage(null, whereParams, page, 10, 10, null);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "查询城市数据异常");
        }
    }
}
